﻿using System;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows.Threading;
using DataStore;
using DataStore.Domain;
using DataStore.Repositories;
using Infrastructure.CurrentData;
using Microsoft.Practices.Composite.Events;

namespace Infrastructure.ViewModels
{
    /// <summary>
    /// AllCountries viewmodel
    /// </summary>
    public class AllCountriesViewModel: DataModel
    {
        ObservableCollection<CountryViewModel> _countries = new ObservableCollection<CountryViewModel>();

        /// <summary>
        /// Initializes a new instance of the <see cref="AllCountriesViewModel"/> class.
        /// </summary>
        public AllCountriesViewModel() : base()
        {
            Initialize();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AllCountriesViewModel"/> class.
        /// </summary>
        /// <param name="eventAggregator">The event aggregator.</param>
        public AllCountriesViewModel(IEventAggregator eventAggregator)
            : base(eventAggregator)
        {
            Initialize();
        }

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        void Initialize()
        {
            State = ModelState.Fetching;

            RefreshCategories();
        }

        /// <summary>
        /// Refreshes the categories.
        /// </summary>
        void RefreshCategories()
        {
            if (!ThreadPool.QueueUserWorkItem(FetchCountriesCallback))
            {
                State = ModelState.Invalid;
            }
        }

        /// <summary>
        /// Gets or sets the countries.
        /// </summary>
        /// <value>The countries.</value>
        public ObservableCollection<CountryViewModel> Countries
        {
            get
            {
                VerifyCalledOnUIThread();
                return _countries;
            }
            set
            {
                VerifyCalledOnUIThread();
                if (_countries != value)
                {
                    _countries = value;
                    OnPropertyChanged("Countries");
                }
            }
        }

        /// <summary>
        /// Fetches the countries callback.
        /// </summary>
        /// <param name="state">The state.</param>
        void FetchCountriesCallback(object state)
        {
            IDatabase database = Current.Container.Resolve<IDatabase>();
            var unitOfWork = database.CreateUnitOfWork();
            IRepository<Country> repository = new CountryRepository(unitOfWork);

            try
            {
                var countries = repository.All;

                Dispatcher.BeginInvoke(
                    new ThreadStart(delegate
                                        {
                                            Countries.Clear();
                                            foreach (var country in countries)
                                            {
                                                Countries.Add(new CountryViewModel(EventAggregator, country));
                                            }

                                            unitOfWork.Dispose();

                                            State = ModelState.Active;
                                            OnLoaded(this, EventArgs.Empty);
                                        }),
                    DispatcherPriority.ApplicationIdle);
            }
            catch (Exception e)
            {
                Log.Error("Failed to load Countries", e);

                unitOfWork.Dispose();
                Dispatcher.BeginInvoke(
                    new ThreadStart(delegate
                                        {
                                            State = ModelState.Invalid;
                                            OnLoaded(this, EventArgs.Empty);
                                        }),
                    DispatcherPriority.ApplicationIdle);

            }
        }
    }
}